package com.maxjay.system.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.maxjay.system.web.controller.struts.AjaxJsonResponse;

public class BaseMultiActionController extends MultiActionController {
	
	private ResourceBundleMessageSource messageSource;

	protected static final String DUPLICATED_KEY_MSG = "common.duplicated.key";

	protected static final String ERROR_PAGE = "error";

	protected static final String ERROR_DIALOG_PAGE = "error_dialog";

	protected static final String ACT_TYPE_ADD = "add";

	protected static final String ACT_TYPE_UPDATE = "update";

	protected static final String ACT_TYPE = "actType";
	
	protected void outputSuccessJsonResponse(HttpServletResponse response, Map<String, Object> customContent) throws IOException {
		String message = getBundleMessage("common.success");
		String responseContent = AjaxJsonResponse.generateSuccessfulOperationDoc(customContent, message);
		flushResponse(response, responseContent);
	}

	protected void outputSuccessJsonResponseMessage(HttpServletResponse response, String customMessage)
			throws IOException {
		String responseContent = AjaxJsonResponse.generateSuccessfulOperationDoc(null, customMessage);
		flushResponse(response, responseContent);
	}

	protected void outputSuccessJsonResponse(HttpServletResponse response, Map<String, Object> customContent, String customMsg)
			throws IOException {
		String responseContent = AjaxJsonResponse.generateSuccessfulOperationDoc(customContent, customMsg);
		flushResponse(response, responseContent);
	}
	
	protected void flushResponse(HttpServletResponse response, String responseContent) throws IOException {
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		writer.write(responseContent);
		writer.flush();
		writer.close();
	}
	
	protected String getBundleMessage(String key) {
		return getBundleMessage(key, null);
	}

	protected String getBundleMessage(String key, Object args[]) {
		if (messageSource == null)
			throw new RuntimeException("MessageSourceAccessor should be injected before you use it!");
		else
			return messageSource.getMessage(key, args, Locale.getDefault());
	}

	public ResourceBundleMessageSource getMessageSource() {
		return messageSource;
	}

	public void setMessageSource(ResourceBundleMessageSource messageSource) {
		this.messageSource = messageSource;
	}

}
